package eu.news.servlet.admin.news;

import java.io.IOException;
import java.net.URLDecoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import eu.news.data.dao.DAOFactory;
import eu.news.data.dao.SpecialDAO;
import eu.news.data.pojo.Special;
import eu.news.kits.Backman;

/**
 * Servlet implementation class EditSpecial
 */
public class EditSpecial extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EditSpecial() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String uri=request.getRequestURI();
		String name=URLDecoder.decode(uri.substring(uri.indexOf("admin/news/special/edit/")+24),"UTF-8");
		if(name.length()>0){
			SpecialDAO spDao=DAOFactory.getSpecialDAO();
			request.setAttribute("sp", spDao.getByName(name));
		}
		request.setAttribute("themes", Backman.ListThemes());
		request.getRequestDispatcher("/admin/news/special/edit.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String uri=request.getRequestURI();
		String name=URLDecoder.decode(uri.substring(uri.indexOf("admin/news/special/edit/")+24),"UTF-8");
		Special sp=null;
		SpecialDAO spDao=DAOFactory.getSpecialDAO();
		if(name.length()>0)
			sp=spDao.getByName(name);
		if(sp==null)
			sp=spDao.newEntity();
		String newName=request.getParameter("name");
		if(spDao.getByName(newName)==null){
			sp.setName(request.getParameter("name"));
			sp.setTheme(request.getParameter("theme"));
			spDao.save(sp);
			spDao.commit();
			request.setAttribute("message", "更新成功");
		}else
			request.setAttribute("message", "同名专题已经存在");
		request.setAttribute("sp", sp);
		request.setAttribute("themes", Backman.ListThemes());
		request.getRequestDispatcher("/admin/news/special/edit.jsp").forward(request, response);
	}

}
